package com.dao.impl;

import com.dao.TypeDAO;
import com.entity.Type;
import com.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/*
 *
 *@author XCH
 *@date2024 - 11 - 27
 *
 */
public class TypeDAOImpl implements TypeDAO {
    @Override
    public List<Type> getAllType() {
        List<Type> types = new ArrayList<>();
        String sql = "select type_id,type_name from product_type";
        System.out.println("sql:"+sql);
        try (Connection conn = DbUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {

            while (rs.next()) {
                Type type = new Type();
                type.setId(rs.getInt("type_id"));
                type.setName(rs.getString("type_name"));
                types.add(type);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return types;

    }

    @Override
    public String getTypeNameById(int id) {
        String sql = "SELECT type_name FROM product_type WHERE type_id = ?";
        try (Connection conn = DbUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, id);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    return rs.getString("type_name");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
